package homework;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class EchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int ServerPort;

    public EchoClient(String serverIp,int ServerPort) throws SocketException{
        this.serverIp = serverIp;
        this.ServerPort = ServerPort;
        socket = new DatagramSocket(); 
    }

    public void start() throws IOException{
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动");

        while (true) {
            //1.从控制台获取用户输入内容
            System.out.println("请输入要发送的内容:");
            String request = scanner.next();
            //2.过造成udp请求，并发送，不光要填内容，是要填服务器的地址和端口号
            DatagramPacket reqPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                InetAddress.getByName(serverIp),ServerPort);
            socket.send(reqPacket);
            //3.读取服务器响应
            DatagramPacket respPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(respPacket);
            String response = new String(respPacket.getData(),0,respPacket.getLength());
            //4.把响应输出到控制台
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        //EchoClient echoClient = new EchoClient("101.200.34.238", 9090);
        EchoClient echoClient = new EchoClient("127.0.0.1", 9090);
        echoClient.start();
    }
}
